import type { LoginInfo, LoginParams, RegisterParams } from '@/api/interface/system/admin/login'
import { ADMIN_MODULE } from '@/api/helper/prefix'
import { http } from '@/utils/http'

// 用户登录
export function loginApi(params: LoginParams) {
  params.grantType = 'password'
  params.clientId = import.meta.env.VITE_APP_CLIENT_ID || 'web'

  // 如果有租户信息，则添加到请求参数中
  const tenantId = uni.getStorageSync('tenantId')
  if (tenantId) {
    params.tenantId = tenantId
  }

  return http.post<LoginInfo>(`${ADMIN_MODULE}/auth/login`, params)
}

// 用户注册
export function registerApi(params: RegisterParams) {
  // 如果有租户信息，确保添加到请求参数中
  if (!params.tenantKey) {
    const tenantId = uni.getStorageSync('tenantId')
    const tenantCode = uni.getStorageSync('tenantCode')
    if (tenantId) {
      params.tenantKey = tenantId
    }
    else if (tenantCode) {
      params.tenantKey = tenantCode
    }
  }

  return http.post<void>(`${ADMIN_MODULE}/client/sys-user/auth/register`, params)
}

// 获取菜单列表
export function getAuthMenuListApi() {
  return http.get<Menu.MenuOptions[]>(`${ADMIN_MODULE}/sys-menu/menu`)
}

// 获取按钮权限
export function getAuthButtonListApi() {
  return http.get<string[]>(`${ADMIN_MODULE}/sys-menu/btn/permissions`)
}

// 用户退出登录
export function logoutApi() {
  return http.post(`${ADMIN_MODULE}/auth/logout`)
}

// 获取用户角色
export function getAuthRoleListApi() {
  return http.get<string[]>(`${ADMIN_MODULE}/sys-menu/user/roles`)
}
